package edu.washington.cs.workflow.analysis.guistructure.uievents;

import org.uispec4j.ListBox;
import org.uispec4j.Panel;
import org.uispec4j.UIComponent;

import edu.washington.cs.workflow.analysis.guistructure.uievents.UIEvent.WINDOW;
import edu.washington.cs.workflow.util.Utils;

public class ListBoxEvent extends AbstractUIEvent  {

	private final ListBox listBox;
	private final UIAction action;
	private final int selectedIndex;
	
	public ListBoxEvent(ListBox listBox, Panel panel,
			UIAction action, int selectedIndex) {
		Utils.checkNotNull(listBox);
		Utils.checkNotNull(panel);
		Utils.checkNotNull(action);
		Utils.checkTrue(action.equals(UIAction.Click) || action.equals(UIAction.DoubleClick)
				|| action.equals(UIAction.RightClick), "illegal action: " + action);
		this.listBox = listBox;
		this.setCurrentPanel(panel);
		this.action = action;
		Utils.checkTrue(selectedIndex >= 0, "illegal: " + selectedIndex);
		this.selectedIndex = selectedIndex;
	}
	
	@Override
	public UIComponent getUIComponent() {
		return this.listBox;
	}

	@Override
	public UIAction getAction() {
		return this.action;
	}
	
	public int getSelectedIndex() {
		return this.selectedIndex;
	}

	@Override
	public String toString() {
		return this.action + " ListBox: " + this.listBox + ", selectedIndex" + this.selectedIndex;
	}
	
	@Override
	public String getDescription() {
		return this.action + " ListBox: " + this.listBox.getLabel() + 
		     this.listBox.getName() + ", selectedIndex" + this.selectedIndex;
	}

	@Override
	protected WINDOW probeWindowInfoInternal() {
		return WINDOW.NONE;
	}
	
	@Override
	public boolean canFireEvent() {
		return this.listBox.isEnabled().isTrue();
	}
	
	@Override
	protected UIEventOutcome fireEventInternal() {
		
		UIEventOutcome outcome = new UIEventOutcome();
		Throwable error = null;
		try {
			if(this.action.equals(UIAction.Click)) {
				this.listBox.click(selectedIndex);
			} else if (this.action.equals(UIAction.DoubleClick)) {
				this.listBox.doubleClick(selectedIndex);
			} else if (this.action.equals(UIAction.RightClick)) {
				this.listBox.rightClick(selectedIndex);
			}
		}  catch (Throwable e) {
			error = e;
		}
		
		if(error != null) {
		    outcome.setError(error);
		}
		outcome.currentPanelClosed(super.isCurrentPanelClosed());
		return outcome;
	}

}
